<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>餐饮点菜管理系统</h2>
        <p>后台管理登录</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            size="large"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item prop="userType">
          <el-radio-group v-model="loginForm.userType" class="user-type-group">
            <el-radio value="admin" size="large">管理员</el-radio>
            <el-radio value="user" size="large">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item prop="captchaCode">
          <div class="captcha-container">
            <el-input 
              v-model="loginForm.captchaCode" 
              placeholder="请输入验证码" 
              prefix-icon="Key"
              size="large"
              class="captcha-input"
            />
            <div class="captcha-image" @click="getCaptcha">
              <img :src="captchaImage" alt="验证码" v-if="captchaImage">
              <div class="loading" v-else>加载中...</div>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-button" 
            @click="handleLogin"
            :loading="loading"
            block
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'

// 引入登录API
import { login, getCaptcha as getCaptchaAPI } from '@/api/auth'

const router = useRouter()
const loginFormRef = ref()

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: 'admin12345',
  userType: 'admin', // 默认选择管理员
  captchaCode: ''
})

// 登录验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  captchaCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 状态控制
const loading = ref(false)
const captchaImage = ref('')
const currentCaptchaId = ref('')
const captchaError = ref(false)

// 获取验证码
const getCaptcha = async () => {
  try {
    console.log('开始获取验证码...')
    const response = await getCaptchaAPI()
    console.log('验证码API响应:', response)
    
    // 处理响应
    if (response.code === 200) {
      console.log('验证码图片数据:', response.data.image)
      console.log('验证码ID:', response.data.captchaId)
      
      captchaImage.value = response.data.image
      currentCaptchaId.value = response.data.captchaId
      captchaError.value = false
      
      // 检查图片数据是否有效
      if (!captchaImage.value) {
        console.error('验证码图片数据为空')
        ElMessage.error('验证码图片数据为空')
      }
    } else {
      console.error('获取验证码失败，响应码:', response.code, '消息:', response.message)
      ElMessage.error(response.message || '获取验证码失败')
      captchaError.value = true
      captchaImage.value = ''
    }
  } catch (err) {
    console.error('获取验证码异常:', err)
    ElMessage.error('网络错误，无法获取验证码，请检查网络连接或稍后重试')
    // 设置默认的测试验证码图像以便调试
    captchaImage.value = ''
    captchaError.value = true
  }
}

// 处理登录
const handleLogin = () => {
  if (!loginFormRef.value) return
  
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 如果验证码获取失败，阻止登录
    if (captchaError.value) {
      ElMessage.error('验证码服务不可用，请稍后再试')
      return
    }
    
    loading.value = true
    try {
      const params = {
        username: loginForm.username,
        password: loginForm.password,
        userType: loginForm.userType,
        captchaCode: loginForm.captchaCode,
        captchaId: currentCaptchaId.value
      }
      
      console.log('登录请求参数:', params)
      
      const response = await login(params)
      
      // 处理登录响应
      if (response.code === 200) {
        // 登录成功
        ElMessage.success(response.message || '登录成功')
        // 保存token到localStorage（只保存实际的token部分，不包含Bearer前缀）
        const token = response.data.token.replace('Bearer ', '');
        console.log('保存到localStorage的token:', token) // 调试日志
        localStorage.setItem('admin-token', token)
        // 检查用户类型和权限
        if (loginForm.userType === 'admin') {
          // 管理员登录
          if (response.data.isAdmin === true || response.data.isAdmin === "true") {
            // 跳转到管理员首页
            router.push('/')
          } else {
            ElMessage.error('您没有管理员权限')
            // 刷新验证码
            getCaptcha()
            return
          }
        } else {
          // 普通用户登录 - 这里可以跳转到用户页面
          if (response.data.isAdmin === false || response.data.isAdmin === "false") {
            ElMessage.error('后台管理系统不支持普通用户登录，请使用小程序')
            // 刷新验证码
            getCaptcha()
            return
          }
        }
      } else {
        // 登录失败，根据错误信息显示具体错误
        if (response.message) {
          ElMessage.error(response.message)
        } else {
          ElMessage.error('登录失败')
        }
        // 刷新验证码
        getCaptcha()
      }
    } catch (err) {
      console.error('登录请求失败:', err)
      // 显示具体的错误信息
      if (err.response && err.response.data && err.response.data.message) {
        ElMessage.error(err.response.data.message)
      } else if (err.message) {
        ElMessage.error(err.message)
      } else {
        ElMessage.error('登录失败，请检查用户名、密码和验证码')
      }
      getCaptcha()
    } finally {
      loading.value = false
    }
  })
}

// 页面加载时获取验证码
onMounted(() => {
  getCaptcha()
})
</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-top: 20px;
}

.user-type-group {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-image .loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 12px;
  color: #999;
}

.login-button {
  margin-top: 20px;
}
</style>